//
//  VideoListModel.m
//  VideoPlayer
//
//  Created by 白璐 on 16/9/18.
//  Copyright © 2016年 baidu. All rights reserved.
//

#import "VideoListModel.h"

@interface  VideoListModel ()
@end

@implementation VideoListModel

- (instancetype)init {
    if (self = [super init]) {
        _videoList = [NSMutableArray array];
    }
    
    return self;
}

- (void)loadResource {
    NSString* parentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString* filename = [parentPath stringByAppendingPathComponent:kDefaultUserFilename];
    
    NSFileManager* fm = [NSFileManager defaultManager];
    NSArray* videoList;
    if (![fm fileExistsAtPath:filename]) {
        filename = [[NSBundle mainBundle] pathForResource:kDefaultVideoFilename ofType:nil];
    }
    
    videoList = [NSArray arrayWithContentsOfFile:filename];
    
    for (NSDictionary* dict in videoList) {
        VideoItem* item = [[VideoItem alloc] init];
        item.img = [dict objectForKey:@"img"];
        item.title = [dict objectForKey:@"title"];
        item.detail = [dict objectForKey:@"detail"];
        item.url = [dict objectForKey:@"url"];
        item.token = [dict objectForKey:@"token"];
        [self.videoList addObject:item];
    }
}

- (void)saveResource {
    NSMutableArray* array = [NSMutableArray array];
    for (VideoItem* item in self.videoList) {
        NSMutableDictionary* dict = [NSMutableDictionary dictionary];
        [dict setObject:item.img forKey:@"img"];
        [dict setObject:item.title forKey:@"title"];
        [dict setObject:item.detail forKey:@"detail"];
        [dict setObject:item.url forKey:@"url"];
        if (item.token) {
            [dict setObject:item.token forKey:@"token"];
        }
        [array addObject:dict];
    }
    
    NSString* parentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString* filename = [parentPath stringByAppendingPathComponent:kDefaultUserFilename];
    [array writeToFile:filename atomically:YES];
}

@end
